package com.taokatao.cardmee.business.cardcrud;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.common.widget.AlertDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;


/**
 * 通过扫描二维码、条形码、商品码来自动填充需被输入的卡号
 */
public class CardCodeScanActivity extends BaseActivity implements ZBarScannerView.ResultHandler, View.OnClickListener {

    @BindView(R.id.view_zbar_scanner) ZBarScannerView mScannerView;
    @BindView(R.id.v_fit) View vFit;
    @BindView(R.id.i_back) ImageView iBack;
    @BindView(R.id.i_light) ImageView iLight;
    @BindView(R.id.t_title) TextView tTitle;
    @BindView(R.id.t_pass_2_input) View tPass2Input;

    private String launcherMode;
    private boolean justOnceScan;
    private boolean isLightMode;

//    private AlertDialog dlgError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_capture_add_by_scan);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final int statusBarHeight = Utils.calcStatusBarHeight(this);
            vFit.getLayoutParams().height += statusBarHeight;
        }

        launcherMode = getIntent().getStringExtra("launcher_mode");
        tTitle.getPaint().setFakeBoldText(true);
        tTitle.setText(getIntent().getStringExtra("extra_name"));
    }

    @Override
    @OnClick({R.id.i_back, R.id.i_light, R.id.t_pass_2_input})
    public void onClick(View v) {
        if (v == iBack) {
            onBackPressed();
        } else if (v == iLight) {
            Utils.onMobEvent(this, "clickFlashlight");
            isLightMode = !isLightMode;
            mScannerView.setFlash(isLightMode);
        } else if (v == tPass2Input) {
            Utils.onMobEvent(this, "clickManualInput");
            if (TextUtils.equals(launcherMode, "add")) {
                //
            } else if (TextUtils.equals(launcherMode, "input")) {
            }
            finish();
        }
    }

    @Override
    public void handleResult(Result rawResult) {
        if (justOnceScan) return;
        justOnceScan = true;

        // Do something with the result here
        Utils.logd("handleResult type:" + rawResult.getBarcodeFormat().getName() + " #content:" + rawResult.getContents());
        // If you would like to resume scanning, call this method below:
        mScannerView.resumeCameraPreview(this);

        if (TextUtils.equals(launcherMode, "add")) {
            Intent intent = new Intent(this, CardAddByCodeActivity.class);
            intent.putExtra("extra_card_store", getIntent().getSerializableExtra("extra_card_store"));
            intent.putExtra("extra_format", rawResult.getBarcodeFormat().getName());
            intent.putExtra("extra_content", rawResult.getContents());
            startActivity(intent);
        } else if (TextUtils.equals(launcherMode, "input")) {
            Intent resultIntent = new Intent();
            resultIntent.putExtra("extra_format", rawResult.getBarcodeFormat().getName());
            resultIntent.putExtra("extra_content", rawResult.getContents());
            setResult(RESULT_OK, resultIntent);
        }

        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();          // Start camera on resume

//        mScannerView.postDelayed(runFuncCheck, 1500);
    }

//    final Runnable runFuncCheck = new Runnable() {
//        @Override
//        public void run() {
//            Utils.loge("CardCodeScanActivity onResume scanner post getChildCount %d", mScannerView.getChildCount());
//
//            // 有权限的时候childCount是22#没有权限的时候childCount是20
//            if (mScannerView.getChildCount() < 2 && !isFinishing()) {
//                showErrorDialog();
//            }
//        }
//    };

//    private void showErrorDialog() {
//        if (dlgError == null ) {
//            dlgError = new AlertDialog.Builder(this).setTitle("提示").setMessage("无法打开摄像头，请检查是否给卡蜜开启了相关权限")
//                    .setCancelable(false)
//                    .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    }).create();
//        }
//        dlgError.show();
//    }

    @Override
    protected void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause

//        mScannerView.removeCallbacks(runFuncCheck);
    }
}